package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author stone
 * @date 2022/01/07 14:25
 */
@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    //jackson
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        //Integer[] → String
        try {
            String value = objectMapper.writeValueAsString(integers);
            //给对应序号的占位符提供值
            preparedStatement.setString(i, value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    //String → Integer[]
    @Override
    public Integer[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        try {
            String result = resultSet.getString(columnName);
            Integer[] integers = objectMapper.readValue(result, Integer[].class);
            return integers;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Integer[0];
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        try {
            String result = resultSet.getString(columnIndex);
            Integer[] integers = objectMapper.readValue(result, Integer[].class);
            return integers;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Integer[0];
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        try {
            String result = callableStatement.getString(i);
            Integer[] integers = objectMapper.readValue(result, Integer[].class);
            return integers;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Integer[0];
    }
}
